package com.lingyun.admin.controller.common;

import com.lingyun.common.config.LingYunConfig;
import com.lingyun.common.exception.FileSizeLimitExceededException;
import com.lingyun.common.exception.InvalidExtensionException;
import com.lingyun.common.exception.LyException;
import com.lingyun.common.utils.AjaxResult;
import com.lingyun.common.utils.EditorResult;
import com.lingyun.common.utils.file.FileUploadUtils;
import com.lingyun.common.utils.file.FileUtils;
import com.lingyun.common.utils.redis.RedisUtils;
import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author 没事别雪JAVA
 *
 */

@RestController
@RequestMapping("/common")
public class CommonController {

    @Resource
    RedisUtils redisUtils;

    /**
     *  通用上传请求
     *
     * @param file 图片
     * @return 图片路径
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) {
        try {
            // 上传并返回新文件名称
            String imgPath = FileUploadUtils.upload(LingYunConfig.getImagePath(), file);
            return AjaxResult.success("上传成功",imgPath);
        } catch (FileSizeLimitExceededException e) {
            return AjaxResult.error("文件过大");
        }catch (InvalidExtensionException e) {
            return AjaxResult.error("文件格式错误");
        }catch (IOException e) {
            return AjaxResult.error("上传失败");
        }
    }


    /**
     *
     * wangEditor 图片上传（根据wangEditor要求的格式返回）
     *
     * @param file 图片
     * @return 图片路径
     */
    @PostMapping("/editorFile")
    @ResponseBody
    public EditorResult editorFile(MultipartFile file) {

        try {
            // 上传并返回新文件名称
            String imgPath = FileUploadUtils.upload(LingYunConfig.getImagePath(), file);

            HashMap<String, Object> img = new HashMap<>();
            img.put("url",imgPath);
            img.put("alt",imgPath.substring(imgPath.lastIndexOf("/")+1));
            img.put("href",imgPath);
            EditorResult editorResult=EditorResult.success(img);
            return editorResult;
        } catch (FileSizeLimitExceededException e) {
            return EditorResult.error("文件过大");
        }catch (InvalidExtensionException e) {
            return EditorResult.error("文件格式错误");
        }catch (IOException e) {
            return EditorResult.error("上传失败");
        }
    }




    /**
     * 通用下载请求
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) throws LyException {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new LyException("文件名称({})非法，不允许下载。 ", fileName);
            }
            //String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String realFileName = fileName.substring(fileName.indexOf("_") + 1);
            String filePath = LingYunConfig.getFilePath() +"/"+ fileName;
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            throw new LyException("下载文件失败",e.getMessage());
        }
    }



    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode() throws IOException {
        AjaxResult ajax = AjaxResult.success();

        // png类型
        //SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);

        // 算术类型
        ArithmeticCaptcha specCaptcha = new ArithmeticCaptcha(130, 48, 2);

        String verCode = specCaptcha.text().toLowerCase();
        String key = UUID.randomUUID().toString();
        // 存入redis并设置过期时间为30分钟
        redisUtils.setCacheObject(key, verCode, 30, TimeUnit.MINUTES);

        ajax.put("keyCode", key);
        ajax.put("image", specCaptcha.toBase64());
        return ajax;
    }















}
